package com.zadtek.sharkRider.activity.common;

import java.text.DecimalFormat;

/**
 * 根据经纬度来计算出距离
 * 
 * @author Administrator
 * 
 */
public class Distance {

	private static final double EARTH_RADIUS = 6378137.0;

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	// 将m转为km并保留2位小数点
	private static String getkm(double distance) {
		distance = distance * 0.001;
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(distance);
	}

	// 根据2个经纬度来计算距离(千米单位)
	public static String getDistance(double longitude1, double latitude1,
			double longitude2, double latitude2) {
		double Lat1 = rad(latitude1);
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;
		double b = rad(longitude1) - rad(longitude2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(Lat1) * Math.cos(Lat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return getkm(s);
	}

	// 根据2个经纬度来计算距离
	public static String getDistance(String longitude1, String latitude1,
			String longitude2, String latitude2) {
		String s = "";
		if (longitude1 != null && !longitude1.equals("")) {
			double longtu1 = Double.parseDouble(longitude1);
			double latitu1 = Double.parseDouble(latitude1);
			if (longitude2 != null && !longitude2.equals("")) {
				double longtu2 = Double.parseDouble(longitude2);
				double latitu2 = Double.parseDouble(latitude2);
				s = getDistance(longtu1, latitu1, longtu2, latitu2);
			}
		}
		return s;
	}

}
